# -*- coding: utf-8 -*-
import os
import logging
import _winreg
from ctypes import windll
user32 = windll.user32

from win32con import *

import win32api
import win32con
import win32security
import ntsecuritycon as con

from win32com.shell import shell, shellcon

import Image
from .Desktop import Desktop

class WindowsDesktop(Desktop):
	"""
	Windows Features
	"""
	def loadCurrentWallpaper(self):
		"""
		Attempt to load the current wallpaper from disk and blur it
		"""
		try:
			r = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER)
			bgKey = r'Control Panel\Desktop'
			i = _winreg.OpenKey(r, bgKey)
			wp =_winreg.QueryValueEx(i,'Wallpaper')[0]
			img = Image.open(wp)
			self.bgImage.paste(img, (0, 0))
		except:
			logging.error("LoadCurrent", exc_info = True)

	def setWallpaperStyleSingle(self):		
		"""
		Set the wallpaper for a single monitor
		"""
		# 0x80000001 == HKEY_CURRENT_USER
		k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,
								  r"Control Panel\Desktop", 0,
								  win32con.KEY_SET_VALUE)
		win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "0")
		win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0")

	def setWallpaperStyleMulti(self):
		"""
		Set the wallpaper for multiple monitor configuration
		"""
		# To set a multi-monitor wallpaper, we need to tile it...
		# 0x80000001 == HKEY_CURRENT_USER
		k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,
								  r"Control Panel\Desktop", 0,
								  win32con.KEY_SET_VALUE)
		win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "0")
		win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "1")

	def setWindowsPerms(self, filename):
		everyone, _domain, _type = win32security.LookupAccountName ("", "Everyone")
		dacl = win32security.ACL()
		dacl.AddAccessAllowedAce(win32security.ACL_REVISION,
								 con.FILE_ALL_ACCESS, everyone)

		sd = win32security.GetFileSecurity(filename,
										   win32security.DACL_SECURITY_INFORMATION)
		
		sd.SetSecurityDescriptorDacl(1, dacl, 0)

	def setWallPaperFromBmp(self, pathToBmp):
		
		"""
		Given a path to a bmp, set it as the wallpaper

		:param pathToBmp: Set the windows wallpaper
		"""
		# Set it and make sure windows remembers the wallpaper we set.
		result = user32.SystemParametersInfoA(
			SPI_SETDESKWALLPAPER, 0,
			pathToBmp,
			SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE)

		if not result:
			raise Exception("Unable to set wallpaper.")

	def setWallpaper(self):
		"""
		Set the wallpaper		
		"""
		self.setWallpaperStyle()

		# Save the new wallpaper in our current directory.
		newPath = os.getcwd()
		newPath = os.path.join(newPath, 'pywallpaper.jpg')
		self.bgImage.save(newPath, "JPEG", quality = 90)
		self.setWallPaperFromBmp(newPath)

	def setWallpaperStyle(self):
		"""
		If we have multiple monitors, set the style to "Tiled", otherwise
		we want to set tiling off
		"""
		if len(self.monitors) > 1:
			self.setWallpaperStyleMulti()
		else:
			self.setWallpaperStyleSingle()
